#! /usr/bin/python
import glob, sys, os, time

def convertTimeStr(timeStr):
  t = time.mktime(time.strptime(timeStr, '%Y-%m-%d %H:%M:%S'))
  return int(t * 1000)

def dumpOutdoorData(inDir, outDir):
  dataFileList = glob.glob(inDir + '/*')
  for dataFile in dataFileList:
    tmp = dataFile.split('_')
    # print tmp
    tmp = tmp[-1].split('-')
    # print tmp
    nodeID = int(tmp[0]) + int(tmp[-1])
    print 'found node:', nodeID

    dfile = open(dataFile)
    outfile = open(outDir + '/node' + str(nodeID) + '.csv', 'w')
    msgCnt = 0
    for aline in dfile:
      msg = []
      tmp = aline.split(' ')
      msgCnt += 1

      # hack for slug local time:
      slugTime = int(tmp[17])
      if nodeID == 6:
        slugTime += 325799676
      if nodeID == 7:
        slugTime += 325799676
      if nodeID == 8:
        slugTime += 325799676

      msgTime = time.ctime(slugTime)
      localSeq = int(tmp[15],16) * 256 + int(tmp[16],16)
      msg.append(msgTime);
      msg.append(str(msgCnt))
      for t in tmp[0:15]:
        msg.append(str(int(t,16)))
      msg.append(str(slugTime*1000))
      # msg.append(str(int(time.time()*1000)))

      msg.append(str(localSeq))


      buf = ','.join(msg)

      outfile.write(buf)
      outfile.write('\n')
    outfile.close()
    dfile.close()






def usage():
  print 'convertOutDoor.py <input data dir> <output data dir>'

"""
Main method
"""
def main():

  if(len(sys.argv) != 3):
    usage()
    sys.exit(0)

  inDir = sys.argv[1]
  outDir = sys.argv[2]

  if not os.path.exists(outDir):
    os.mkdir(outDir)
    print 'output data dir:',outDir
    dumpOutdoorData(inDir, outDir)
  else:
    print 'output data dir exists:', outDir

if __name__ == '__main__': main()

